<?php

namespace MyBlog\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use MyBlog\Models\Manager;
use MyBlog\Models\Member;
use Symfony\Component\HttpFoundation\Request;

class Authenticate
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response ('Unauthorized.', 401);
            } elseif(str_contains($request->path(), 'backend')) {
                return redirect()->guest('/backend/login');
            } else {
                return redirect()->guest('/login');
            }
        }else{
            if(Auth::user() instanceof Member && str_contains($request->path(), 'backend')) {
                return Redirect::to('/backend/index');
            }
        }

        return $next($request);
    }
}
